package com.mindao.app.ued.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.mindao.app.common.spring.controller.BaseController;
import com.mindao.app.common.spring.model.BaseModel;
import com.mindao.app.common.spring.service.util.JsonResult;
import com.mindao.app.ea.model.Organize;
import com.mindao.app.ea.model.ZTreeNodeVO;
import com.mindao.app.ea.service.OrganizeService;
import com.mindao.utils.json.JsonUtil;

@Controller
@RequestMapping("/ued/tree")
public class TreeController extends BaseController<Organize> {
	private final Logger log = LoggerFactory.getLogger(TreeController.class);
	
	@Autowired
	protected OrganizeService organizeService;
 
	/**
	 * 加载树
	 * @param response
	 * @param request
	 * @param session
	 * @param rhs
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public String menu_tree (HttpServletResponse response,HttpServletRequest request,HttpSession session,Model rhs ) throws Exception {
		String clickEvent="doEditTree({SID}, {pSid})";
		List<ZTreeNodeVO> nodes= organizeService.loadZtreeData(null,clickEvent);
		String nodesStr=JSON.toJSONString(nodes);
		rhs.addAttribute("treeNodes", nodesStr);
		String selectNodeId=getpara("selectNodeId");
		Organize selectObj=null;
		if (!"".equals(selectNodeId)){
			rhs.addAttribute("selectNodeId",selectNodeId);
			selectObj=(Organize)baseService.loadById(Organize.class, Long.valueOf(selectNodeId));
			rhs.addAttribute("obj", selectObj);
 
		}else{
			if (nodes.size()>0){
				rhs.addAttribute("selectNodeId", nodes.get(0).getId());
				selectObj=(Organize)baseService.loadById(Organize.class,nodes.get(0).getId());
				rhs.addAttribute("obj", selectObj);
			}
		}
		//判断选择节点是否可以下移
		rhs.addAttribute("downable", organizeService.judgeMoveDownable(selectObj));
		rhs.addAttribute("upable", organizeService.judgeMoveUpable(selectObj));
		return super.rtnDefault(request, response, session, rhs);
	}
	/**
	 * 加载某个对象
	 * @param response
	 * @param request
	 * @param session
	 * @param rhs
	 * @return
	 * @throws Exception
	 */
	@Override
	@RequestMapping
	public String edit(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs,@RequestParam (required = false) String id) throws Exception {
		String pId=getpara("pId");
		if (!"".equals(pId)){
			rhs.addAttribute("parentModel", baseService.loadById(Organize.class, Long.valueOf(pId)));
		}
		if (!StringUtils.isBlank(id)){
			Organize selectObj=(Organize)baseService.loadById(Organize.class, Long.valueOf(id));
			//判断选择节点是否可以下移
			rhs.addAttribute("downable", organizeService.judgeMoveDownable(selectObj));
			rhs.addAttribute("upable", organizeService.judgeMoveUpable(selectObj));
		}
		
		return super.edit(request, response, session, rhs, id);
 
	}
	/**
	 * 保存某个对象
	 * @param response
	 * @param request
	 * @param session
	 * @param rhs
	 * @return
	 * @throws Exception
	 */
	@Override
	@RequestMapping( method = RequestMethod.POST)
	public String save(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs, Organize obj ) throws Exception {
		//BaseModel bfobject=(BaseModel)obj;
		String msg=null;
		String status=JsonResult.SUCCESS;
		Organize parentModel=null;
		String pId=getpara("pId");
		if (!"".equals(pId)){
			parentModel=(Organize) baseService.loadById(Organize.class, Long.valueOf(pId));
		}
		if (obj.getDisabled()==null){
			obj.setDisabled(0);
		}
		if (obj.getId() == null || obj.getId().toString().equals("")) { // create
			obj.setParentModel( parentModel);
			obj.setSortNob(organizeService.getNextSortNo("".equals(pId)?null:Long.valueOf(pId)));
			baseService.create(obj);
			msg="新建成功！";
		} else { // edit
			//避免父子关系错乱检查
			if (organizeService.judgeParentRelation(obj, parentModel)){
				Organize newObj= (Organize)baseService.update(obj);
			
				newObj.setParentModel((Organize)parentModel);
				baseService.updateDirectly(newObj);
				msg="更新成功！";
			}else{
				status=JsonResult.ERROR;
				msg="父子关系混乱，保存失败，请检查!";
			}
		}
		
		JsonResult json = new JsonResult();
		json.setStatus(status);
		json.setMessage(msg);
		json.setData(obj.getId()+"");
		JsonUtil.writeJson(json, response.getWriter());
		return null;
	}
	/**
	 * 上下移动某个对象
	 * @param response
	 * @param request
	 * @param session
	 * @param rhs
	 * @return
	 * @throws Exception
	 */
 
	@RequestMapping( method = RequestMethod.POST)
	public String move(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs, @RequestParam (value="id") Long id,@RequestParam (value="upside") Integer upside ) throws Exception {
		String msg=null;
		BaseModel parentModel=null;
		if (id!=null) {  
			 Organize obj=(Organize) baseService.loadById(Organize.class, Long.valueOf(id));
			 organizeService.move(id, obj.getParentModel()==null?null:obj.getParentModel().getId(), upside==1?true:false);
		}
		
		JsonResult json = new JsonResult();
		json.setStatus(JsonResult.SUCCESS);
		json.setMessage(msg);
		json.setData(id);
		JsonUtil.writeJson(json, response.getWriter());
		return null;
	}
	
	/**
	 * 保存某个对象
	 * @param response
	 * @param request
	 * @param session
	 * @param rhs
	 * @return
	 * @throws Exception
	 */
	@Override
	@RequestMapping( method = RequestMethod.POST)
	public String delete(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs, String id  ) throws Exception {
		//BaseModel bfobject=(BaseModel)obj;
 
		Organize obj=null;
		if (id!=null){
			//obj=(Organize) baseService.loadById(Organize.class, Long.valueOf(id));
			//baseService.delete(obj);
			organizeService.deleteResursively(Long.valueOf(id));

		}
	 
		
		JsonResult json = new JsonResult();
		json.setStatus(JsonResult.SUCCESS);
		json.setMessage("删除成功");
		json.setData(id);
		JsonUtil.writeJson(json, response.getWriter());
		return null;
	}
	
	@RequestMapping(  )
	public String select(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs, @RequestParam boolean isMultiple,@RequestParam String selectNodeId ,@RequestParam boolean includeDisabled) throws Exception {
		List<ZTreeNodeVO> nodes=null;
		if (includeDisabled){
			nodes= organizeService.loadZtreeData(null,null);
		}else{
			nodes= organizeService.loadZtreeData(0,null);
		}
		String nodesStr=JSON.toJSONString(nodes);
		rhs.addAttribute("treeNodes", nodesStr);
		//String selectNodeId=getpara("selectNodeId");
		if (!StringUtils.isBlank(selectNodeId)){
			rhs.addAttribute("selectNodeId",selectNodeId);
		}
		return super.rtnDefault(request, response, session, rhs);
	}
}
